package cn.csc.module.order.config;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.resources.ConnectionProvider;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @author liuchuang
 * @version 1.0
 * @date 2024/7/29 11:35
 * @modify
 */
@Configuration
public class WebConfig {

    @Value("csc.park.url")
    private String parkUrl;

    @Bean
    public WebClient webClient(){
        //配置固定大小连接池
        ConnectionProvider provider = ConnectionProvider
                .builder("custom")
                // 等待超时时间
                .pendingAcquireTimeout(Duration.ofSeconds(10))
                // 最大连接数
                .maxConnections(100)
                // 最大空闲时间
                .maxIdleTime(Duration.ofSeconds(5))
                // 最大等待连接数量, -1 挂起队列时，挂起队列将没有上限。默认为2 * max连接数
                .pendingAcquireMaxCount(-1)
                .build();

        HttpClient httpClient = HttpClient.create(provider);
        httpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
        httpClient.responseTimeout(Duration.ofMillis(3000));
        httpClient.doOnConnected(conn -> {
                conn.addHandlerLast(new ReadTimeoutHandler(3000, TimeUnit.MILLISECONDS));
                conn.addHandlerLast(new WriteTimeoutHandler(3000, TimeUnit.MILLISECONDS));
        });

        return WebClient.builder()
                .baseUrl(parkUrl)
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }

}
